package com.helloandroid.dialogs

import android.app.Activity
import android.content.Context
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSeekBar
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.ads.NativeAdUtil
import com.helloandroid.base.BaseDialog
import com.helloandroid.tools.GUtils
import java.lang.Exception

class BsTargetDialog(context:Context) : BaseDialog(context),SeekBar.OnSeekBarChangeListener {

    lateinit var sbBar:AppCompatSeekBar
    lateinit var tvTarget:TextView
    lateinit var tvInfo:TextView

    override fun getContentViewResId() = R.layout.dialog_bs_target

    override fun initView() {

        val user = AppUtil.user
        tvTarget = findViewById(R.id.tvTarget)
        tvInfo = findViewById(R.id.tvInfo)

        tvTarget.text = user.bs_target.toString()

        updateInfo(user.bs_target)

        sbBar = findViewById(R.id.sbBar)
        sbBar.progress = user.bs_target
        sbBar.setOnSeekBarChangeListener(this)

        findViewById<Button>(R.id.btnClose).setOnClickListener {
            val old =  user.bs_target
            val cur =  tvTarget.text.toString().toInt()
            if(old != cur){
                //  提交这个更改目标步数的请求
                AppUtil.appViewModel().chgTarget(cur)
            }
            cancel()
        }

//        NativeAdUtil.showNativeAd(ctx as Activity,findViewById(R.id.nativeView))
    }

    override fun initData() {
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

        try {
            val oldNum = tvTarget.text.toString().toInt()
            if(oldNum == progress){
                return
            }
        }catch (ex:Exception){

        }

        var newProgress = progress / 1000;
        newProgress *= 1000;
        sbBar.progress = newProgress
        tvTarget.text = newProgress.toString()
        updateInfo(newProgress)
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
    }


    fun updateInfo(bs:Int){
        val str = String.format("%.2f",bs * GUtils.MeterPerBu / 1000f)
        tvInfo.text = "相当于跑步${str}公里,可有效预防骨质酥松."
    }
}